package com.zhiyou.aifeng.smart_machine

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.aifeng.utils.getExtra
import com.zhiyou.aifeng.common.helper.get
import com.zhiyou.aifeng.common.helper.getString
import com.zhiyou.aifeng.common.helper.putShared
import com.zhiyou.aifeng.common_ui.base.BaseActivity
import com.zhiyou.aifeng.common_ui.utils.bindLifeCycle
import com.zhiyou.aifeng.common_ui.utils.subscribeByFinally
import com.zhiyou.aifeng.viewmodel.MainViewModel
import org.jetbrains.anko.webView

class WeatherActivity : BaseActivity() {

    private lateinit var mWeb: WebView

    @SuppressLint("SetJavaScriptEnabled")
    @Suppress("DEPRECATION")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mWeb = webView {
            overScrollMode = View.OVER_SCROLL_NEVER

            //支持javascript
            settings.javaScriptEnabled = true
            //设置可以支持缩放
            settings.setSupportZoom(true)
            //自适应屏幕
            settings.loadWithOverviewMode = true
            settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
            isHorizontalScrollBarEnabled = false

            //设置出现缩放工具
            settings.builtInZoomControls = false
            settings.displayZoomControls = false

            //设置是否使用缓存
            settings.setAppCacheEnabled(true)
            settings.domStorageEnabled = true

            webChromeClient = WebChromeClient()
            webViewClient = object : WebViewClient() {

                /*
                 * 当加载的网页需要重定向的时候就会回调这个函数告知我们应用程序是否需要接管控制网页加载，
                 * 如果应用程序接管，并且return true意味着主程序接管网页加载，如果返回false让webview自己处理
                 */
                @Suppress("DEPRECATION", "OverridingDeprecatedMember")
                override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                    return true
                }

                /*
                 * 在开始加载网页时会回调
                 */
                override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                    super.onPageStarted(view, url, favicon)
                    showLoading()
                }

                /*
                 * 在结束加载网页时会回调
                 */
                override fun onPageFinished(view: WebView?, url: String?) {
                    super.onPageFinished(view, url)
                    dismissLoading()
                }

            }
        }
        initTitle("天气详情", divider = false)

        getData()
    }

    override fun getViewModel() = get<MainViewModel>()

    override fun getData(index: Int, isLoading: Boolean) {
        val mCity = intent.getExtra("city")
        val mDistrict = intent.getExtra("district")

        if (getString(mCity + mDistrict).isNotEmpty()) {
            val locationId = getString(mCity + mDistrict)

            mWeb.loadUrl(
                "https://widget-page.heweather.net/h5/index.html?bg=1&md=0123456&lc=CN${locationId}&key=a5d68dc0e81446bc92d4548055beed67"
            )
        } else {
            getViewModel().getLocationId(mDistrict)
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByFinally(
                    event = getViewModel(),
                    onSuccess = { data ->
                        val hasName = data.any { it.name in mDistrict && it.adm2 in mCity }
                        if (hasName) {
                            val item = data.first { it.name in mDistrict && it.adm2 in mCity }

                            putShared(mCity + mDistrict, item.id)

                            mWeb.loadUrl(
                                "https://widget-page.heweather.net/h5/index.html?bg=1&md=0123456&lc=CN${item.id}&key=a5d68dc0e81446bc92d4548055beed67"
                            )
                        } else {
                            val hasCity = data.any { it.name in mCity }
                            if (hasCity) {
                                val item = data.first { it.name in mCity }

                                putShared(mCity + mDistrict, item.id)

                                mWeb.loadUrl(
                                    "https://widget-page.heweather.net/h5/index.html?bg=1&md=0123456&lc=CN${item.id}&key=a5d68dc0e81446bc92d4548055beed67"
                                )
                            } else {
                                mWeb.loadUrl(
                                    "https://widget-page.heweather.net/h5/index.html?bg=1&md=0123456&lc=auto&key=a5d68dc0e81446bc92d4548055beed67"
                                )
                            }
                        }
                    }
                )
        }
    }

}